//
//  MainViewController.swift
//  LGMusic
//
//  Created by 梁尚嘉 on 2017/3/31.
//  Copyright © 2017年 LimeGah. All rights reserved.
//

import UIKit
import Alamofire
import SwiftyJSON
class MainViewController: BaseViewController {

    override var preferredStatusBarStyle: UIStatusBarStyle{
        return .default
    }

    fileprivate var searchItem:LGSearchBar?
    fileprivate var searchIconItem:UIBarButtonItem?
    fileprivate var logoItem:UIView?
    fileprivate var tableView:UITableView?
    fileprivate var delegater:BillListDelegater?

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        self.outterPlayBarConfigure()
        self.navigatorConfigure()
        self.searchBarConfigure()
        self.tableViewConfigure()

    }

    func outterPlayBarConfigure() {
        let billTabsVCtrl = BillTabsViewController()
        self.addChildViewController(billTabsVCtrl)
        self.view .addSubview(billTabsVCtrl.view)
        billTabsVCtrl.view.snp.makeConstraints { (make) in
            make.left.right.top.equalTo(0)
        }
        self.view.addSubview(LGOutPlayBar.sharedBar)
        LGOutPlayBar.sharedBar.snp.makeConstraints { (make) in
            make.left.right.bottom.equalTo(0)
            make.height.equalTo(49)
            make.top.equalTo(billTabsVCtrl.view.snp.bottom)
        }
    }

    func searchBarConfigure() {
        let searchBar = LGSearchBar.init(frame:CGRect.init(x: 0, y: 0, width: SM_SCREEN_SIZE().width, height: LGSearchBarHeight))
        searchBar.textField?.delegate = self;
        searchBar.cancelButton?.addTarget(self, action: #selector(cancelButtonTap), for: UIControlEvents.touchUpInside)
        self.searchItem = searchBar
    }


    func tableViewConfigure() {
        self.tableView = UITableView.init(frame: CGRect.zero, style: UITableViewStyle.plain)
        self.tableView?.delegate = self
        self.tableView?.dataSource = self
        self.tableView?.tableFooterView = UIView()
        self.tableView?.isHidden = true
        self.view.addSubview(self.tableView!)
        self.tableView?.snp.makeConstraints({ (make) in
            make.edges.equalTo(0)
        })
        self.delegater = BillListDelegater.delegater(with: self.tableView!)
    }


    func navigatorConfigure() {
        self.navigationItem.rightBarButtonItem = UIBarButtonItem.init(image: UIImage.init(named: "ic_home_search"), style: UIBarButtonItemStyle.plain, target: self, action: #selector(self.didSearchItemTap))
        self.navigationItem.titleView = UIImageView.init(image: UIImage.init(named: NSLocalizedString("logo", comment: "default")))
        self.logoItem = self.navigationItem.titleView
        self.searchIconItem = self.navigationItem.rightBarButtonItem
    }


    func cancelButtonTap(_ sender:UIButton) -> Void {
        self.navigationItem.titleView = self.logoItem
        self.navigationItem.setRightBarButton(self.searchIconItem, animated: true)
        self.tableView?.isHidden = true
    }


    func didSearchItemTap(_ sender:Any) {
        self.navigationItem.setRightBarButton(nil, animated: true)
        self.navigationItem.titleView = self.searchItem
        self.tableView?.isHidden = false
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}

extension MainViewController : UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 0
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        return BaseTableCell()
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return BaseTableCell.cellHeight()
    }
}


extension MainViewController : UITextFieldDelegate {
    //按钮回车，即「搜索」键
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {

        self.search(textField)
        self.view?.endEditing(true)
        return true
    }

    func search(_ textField: UITextField) -> Void {
        Alamofire.request("http://tingapi.ting.baidu.com/v1/restserver/ting?from=android&version=5.6.5.0&method=baidu.ting.search.merge&format=json&query="+(textField.text?.addingPercentEncoding(withAllowedCharacters: NSCharacterSet(charactersIn:"`#%^{}\"[]|\\<> ").inverted)!)!+"&page_no=1&page_size=50&type=-1&data_source=0&use_cluster=1", method: HTTPMethod.get).responseString { (data) in
            let dictionary = JSON.init(parseJSON: data.value!)
            var bills = [Bill]()
            let billsTempArray = dictionary["result"]["song_info"]["song_list"].array
            if billsTempArray != nil {
                for billdic:JSON in  billsTempArray! {
                    let bill = self.parseWith(billdic)
                    bills.append(bill)
                }
                self.delegater?.bills = bills
            }
        }
    }

    func parseWith(_ billdic:JSON) -> Bill {
        var bill = Bill()
        bill.song_id = billdic["song_id"].string
        bill.title = billdic["title"].string
        bill.artist_id = billdic["artist_id"].string
        bill.artist_name = billdic["author"].string
        bill.album_id = billdic["album_id"].string
        bill.album_title = billdic["album_title"].string
        bill.pic_small = billdic["pic_small"].string
        bill.pic_big = bill.pic_small?.replacingOccurrences(of: "w_90", with: "w_150")
        return bill;
    }


}
